package model

import (
	"errors"
	"haodayizhi/global"
	"time"

	"gorm.io/gorm"
)

const TableNamePurchaseRecord = "purchase_records"

// PurchaseRecord mapped from table <purchase_records>
type PurchaseRecord struct {
	ID                 int64     `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id,string"`
	UserID             int64     `gorm:"column:user_id;type:bigint" json:"userId"`
	ProductID          int64     `gorm:"column:product_id;type:bigint" json:"productId"`
	BuyPrice           float64   `gorm:"column:buy_price;type:decimal(10,2)" json:"buyPrice"`
	BuyQuantity        int64     `gorm:"column:buy_quantity;type:int" json:"buyQuantity"`
	BuyAt              time.Time `gorm:"column:buy_at;type:datetime" json:"buyAt"`
	BuyOrderNumber     string    `gorm:"column:buy_order_number;type:varchar(255)" json:"buyOrderNumber"`
	BuyWay             string    `gorm:"column:buy_way;type:enum('线下支付','线上支付')" json:"buyWay"`
	PaymentCompletedAt time.Time `gorm:"column:payment_completed_at;type:datetime" json:"paymentCompletedAt"`
}

// TableName PurchaseRecord's table name
func (*PurchaseRecord) TableName() string {
	return TableNamePurchaseRecord
}

// CreatePurchaseRecord creates a new PurchaseRecord in the database.
func (m *PurchaseRecord) CreatePurchaseRecord() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetPurchaseRecordByID retrieves a PurchaseRecord by its ID from the database.
func (m *PurchaseRecord) GetPurchaseRecordByID(id int64) (*PurchaseRecord, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // PurchaseRecord not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdatePurchaseRecord updates an existing PurchaseRecord in the database.
func (m *PurchaseRecord) UpdatePurchaseRecord() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeletePurchaseRecord deletes a PurchaseRecord by its ID from the database.
func (m *PurchaseRecord) DeletePurchaseRecord(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}

// 获取购买记录通过用户id
func GetPurchaseRecordByUserID(page, limit int, userID int64) ([]*PurchaseRecord, int64, error) {
	var purchaseRecords []*PurchaseRecord
	var total int64
	if err := global.Db.Where("user_id = ?", userID).Offset((page - 1) * limit).Limit(limit).Find(&purchaseRecords).Error; err != nil {
		return nil, total, err
	}
	// 获取总记录数
	if err := global.Db.Model(&PurchaseRecord{}).Where("user_id = ?", userID).Count(&total).Error; err != nil {
		return nil, total, err
	}
	return purchaseRecords, total, nil
}
